#include "LogicalNetParser.h"

#include "NetClassParser.h"
#include "NonstandardAttributeParser.h"
#include "PinRefParser.h"
#include "QStringParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

LogicalNetParser::LogicalNetParser(
    QStringParser *&_nameParser
    , NetClassParser *&_netClassParser
    , NonstandardAttributeParser *&_nonstandardAttributeParser
    , PinRefParser *&_pinRefParser
):    m_nameParser(_nameParser)
    , m_netClassParser(_netClassParser)
    , m_nonstandardAttributeParser(_nonstandardAttributeParser)
    , m_pinRefParser(_pinRefParser)
{

}

bool LogicalNetParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new LogicalNet());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("name")))
    {
        data = reader->attributes().value(QStringLiteral("name"));
        if (!m_nameParser->parse(reader, data))
            return false;
        m_result->name = m_nameParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("name: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("netClass")))
    {
        data = reader->attributes().value(QStringLiteral("netClass"));
        if (!m_netClassParser->parse(reader, data))
            return false;
        m_result->netClassOptional = Optional<NetClass>(m_netClassParser->result());
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("NonstandardAttribute"))
        {
            if (!m_nonstandardAttributeParser->parse(reader))
                return false;
            auto result = m_nonstandardAttributeParser->result();
            m_result->nonstandardAttributeList.append(result);
        }
        else if (name == QStringLiteral("PinRef"))
        {
            if (!m_pinRefParser->parse(reader))
                return false;
            auto result = m_pinRefParser->result();
            m_result->pinRefList.append(result);
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

LogicalNet *LogicalNetParser::result()
{
    return m_result.take();
}

}